﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxEditors;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Web;

namespace Thi_nghiem_nen_ket_co_thong_tin
{
    public partial class Bieu_do_thi_nghiem : System.Web.UI.UserControl
    {
        public string cap_ap_luc = string.Empty;
        public string he_do_rong = string.Empty;
        public string str_P_0 = string.Empty;
        public string str_e_0 = string.Empty;
        public string str_e_i = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            cap_ap_luc = Hcap_ap_luc.Value;
            he_do_rong = Hhe_do_rong.Value;
            str_P_0 = Hstr_P_0.Value;
            str_e_0 = Hstr_e_0.Value;
            str_e_i = Hstr_e_i.Value;
            if (!IsPostBack)
            {
                InitWebChart();
                Bieu_do_thi_nghiem_Load();
            }
        }

        public void SetHValue(string s_cap_ap_luc, string s_he_do_rong, string s_str_P_0, string s_str_e_0, string s_str_e_i)
        {
            cap_ap_luc=Hcap_ap_luc.Value = s_cap_ap_luc;
            he_do_rong=he_do_rong = Hhe_do_rong.Value;
            str_P_0=Hstr_P_0.Value = s_str_P_0;
            str_e_0=Hstr_e_0.Value = s_str_e_0;
            str_e_i = Hstr_e_i.Value = s_str_e_i;
            switch (cap_ap_luc)
            {
                case "Cấp 1":
                    txt_cap_ap_luc.Text = "12.5";
                    break;
                case "Cấp 2":
                    txt_cap_ap_luc.Text = "25";
                    break;
                case "Cấp 3":
                    txt_cap_ap_luc.Text = "50";
                    break;
                case "Cấp 4":
                    txt_cap_ap_luc.Text = "100";
                    break;
                case "Cấp 5":
                    txt_cap_ap_luc.Text = "200";
                    break;
                case "Cấp 6":
                    txt_cap_ap_luc.Text = "400";
                    break;
                case "Cấp 7":
                    txt_cap_ap_luc.Text = "800";
                    break;
                case "Cấp 8":
                    txt_cap_ap_luc.Text = "1600";
                    break;
                case "Cấp 9":
                    txt_cap_ap_luc.Text = "3200";
                    break;
                case "Cấp 10":
                    txt_cap_ap_luc.Text = "6400";
                    break;
            }
            Bieu_do_thi_nghiem_Load();
        }

        protected void InitWebChart()
        {
            var series1 = new Series("Series1", ViewType.Spline);

            // Specify data members to bind the series.
            series1.ArgumentScaleType = ScaleType.Numerical;
            series1.ArgumentDataMember = "Argument";
            series1.ValueScaleType = ScaleType.Numerical;
            series1.ValueDataMembers.AddRange(new string[] { "Value" });

            // Create an empty Bar series and add it to the chart.
            var series2 = new Series("Series2", ViewType.Line);

            // Specify data members to bind the series.
            series2.ArgumentScaleType = ScaleType.Numerical;
            series2.ArgumentDataMember = "Argument";
            series2.ValueScaleType = ScaleType.Numerical;
            series2.ValueDataMembers.AddRange(new string[] { "Value" });

            var series3 = new Series("Series3", ViewType.Line);
            // Specify data members to bind the series.
            series3.ArgumentScaleType = ScaleType.Numerical;
            series3.ArgumentDataMember = "Argument";
            series3.ValueScaleType = ScaleType.Numerical;
            series3.ValueDataMembers.AddRange(new string[] { "Value" });

            var series4 = new Series("Series4", ViewType.Point);
            // Specify data members to bind the series.
            series4.ArgumentScaleType = ScaleType.Numerical;
            series4.ArgumentDataMember = "Argument";
            series4.ValueScaleType = ScaleType.Numerical;
            series4.ValueDataMembers.AddRange(new[] { "Value" });

            chartControl1.Series.Add(series1);
            chartControl1.Series.Add(series2);
            chartControl1.Series.Add(series3);
            chartControl1.Series.Add(series4);

            // chartControl1.Series.Remove();
            chartControl1.Legend.Visible = false;
            // Dock the chart into its parent and add it to the current form.
            ((XYDiagram)chartControl1.Diagram).AxisX.Title.Visible = true;
            ((XYDiagram)chartControl1.Diagram).AxisX.Title.Alignment = StringAlignment.Center;
            ((XYDiagram)chartControl1.Diagram).AxisX.Title.Text = "Thời gian thí nghiệm";
            ((XYDiagram)chartControl1.Diagram).AxisX.Title.TextColor = Color.Red;
            ((XYDiagram)chartControl1.Diagram).AxisX.Title.Antialiasing = true;
            ((XYDiagram)chartControl1.Diagram).AxisX.Title.Font = new Font("Tahoma", 12, FontStyle.Regular);
            // Customize the appearance of the Y-axis title.
            ((XYDiagram)chartControl1.Diagram).AxisY.Title.Visible = true;
            ((XYDiagram)chartControl1.Diagram).AxisY.Title.Alignment = StringAlignment.Center;
            ((XYDiagram)chartControl1.Diagram).AxisY.Title.Text = "Số đọc";
            ((XYDiagram)chartControl1.Diagram).AxisY.Title.TextColor = Color.Blue;
            ((XYDiagram)chartControl1.Diagram).AxisY.Title.Antialiasing = true;
            ((XYDiagram)chartControl1.Diagram).AxisY.Title.Font = new Font("Tahoma", 12, FontStyle.Regular);

            //Axis AxisX { get { return ((XYDiagram)chartControl1.Diagram).AxisX; } }
            ((XYDiagram)chartControl1.Diagram).AxisX.VisualRange.Auto = true;
            ((XYDiagram)chartControl1.Diagram).AxisY.VisualRange.Auto = false;
            ((XYDiagram)chartControl1.Diagram).AxisY.VisualRange.MaxValue = 1;
            //((XYDiagram)chart.Diagram).AxisY.VisualRange.MinValue = 2;
            //((XYDiagram)chart.Diagram).AxisX.Range.ScrollingRange.SetMinMaxValues(1, 2);
            //((XYDiagram)chart.Diagram).AxisX.VisualRange.SetMinMaxValues(0, 3);chartControl1.DataBind();
        }

        private void Bieu_do_thi_nghiem_Load()
        {
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null)
            {
                obj = new ObjBieuDoThiNghiem();
                // Create an empty Bar series and add it to the chart.
                Session[ObjBieuDoThiNghiem.SESSION_NAME] = obj;
            }

            {
                if (chartControl1.Series["Series1"] != null)
                {
                    chartControl1.Series["Series1"].Points.Clear();
                    //series1.DataSource = obj.Dt1;
                    for (int i = 0; i < obj.Dt1.Rows.Count; i++)
                    {
                        //series1.Points.Add(new SeriesPoint(i, i));
                        var ag = Convert.ToDouble(obj.Dt1.Rows[i][0]);
                        var vl = Convert.ToDouble(obj.Dt1.Rows[i][1]);
                        if (!double.IsInfinity(ag) && !double.IsInfinity(vl)&&!double.IsNaN(ag)&&!double.IsNaN(vl))
                            chartControl1.Series["Series1"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                    }
                }

                if (chartControl1.Series["Series2"] != null)
                {
                    chartControl1.Series["Series2"].Points.Clear();
                    for (int i = 0; i < obj.Dt2.Rows.Count; i++)
                    {
                        var ag = Convert.ToDouble(obj.Dt2.Rows[i][0]);
                        var vl = Convert.ToDouble(obj.Dt2.Rows[i][1]);
                        if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                            chartControl1.Series["Series2"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                    }
                }

                if (chartControl1.Series["Series3"] != null)
                {
                    chartControl1.Series["Series3"].Points.Clear();
                    for (int i = 0; i < obj.Dt3.Rows.Count; i++)
                    {
                        var ag = Convert.ToDouble(obj.Dt3.Rows[i][0]);
                        var vl = Convert.ToDouble(obj.Dt3.Rows[i][1]);
                        if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                            chartControl1.Series["Series3"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                    }
                }

                if (chartControl1.Series["Series4"] != null)
                {
                    chartControl1.Series["Series4"].Points.Clear();
                    for (int i = 0; i < obj.Dt4.Rows.Count; i++)
                    {
                        var ag = Convert.ToDouble(obj.Dt4.Rows[i][0]);
                        var vl = Convert.ToDouble(obj.Dt4.Rows[i][1]);
                        if (!double.IsInfinity(ag) && !double.IsInfinity(vl) && !double.IsNaN(ag) && !double.IsNaN(vl))
                            chartControl1.Series["Series4"].Points.Add(new SeriesPoint(ag, new[] { vl }));
                    }
                }
                
            }
          
            chartControl1.DataBind();
        }

        private DataTable ve_bieu_do()
        {
            var obj = (ObjBieuDoThiNghiem) Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if(obj==null) return null;

            // Create an empty table.
            DataTable table = new DataTable("Table1");

            // Add two columns to the table.
            table.Columns.Add("Argument", typeof(Double));
            table.Columns.Add("Value", typeof(Double));

            // Add data rows to the table.
            DataRow row = null;

            for (int i = 0; i < 14; i++)
            {
                row = table.NewRow();
                if (obj.data_bieu_do == "Biểu thị theo căn(t)")
                    row["Argument"] = Math.Sqrt(obj.data_time[i]);
                else
                {
                    row["Argument"] = Math.Log10(obj.data_time[i]);

                }

                row["Value"] = -obj.data_deformation[i];
                table.Rows.Add(row);
            }
            return table;
        }

        private void tim_tiep_tuyen_1()
        {
            lblError.Text = "";
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null) return;
            obj.average = 0;
            double[] temp = new double[13];
            double[] temp_ordi = new double[13];
            double flag = 0;
            for (int i = 0; i <= 12; i++)
            {
                temp[i] = Math.Atan((obj.data_deformation[i + 1] - obj.data_deformation[i]) / (Math.Log10(obj.data_time[i + 1]) - Math.Log10(obj.data_time[i]))) * 180 / Math.PI;
            }
            for (int i = 0; i <= 11; i++)
            {
                if (Math.Abs(temp[i + 1] - temp[i]) <= 1)
                    temp_ordi[i] = 1;
                else
                    temp_ordi[i] = 0;
            }
            for (int i = 1; i <= 11; i++)
            {
                if (temp_ordi[i] == 1 && temp_ordi[i - 1] + temp_ordi[i] + temp_ordi[i + 1] >= 2)
                {
                    obj.average = obj.average + i;
                    flag = flag + 1;
                }
            }
            if (flag <= 1)
            {
                lblError.Text = "Dữ liệu bị sai... Xem lại dữ liệu !!";
                return;
            }


            obj.average = Math.Round(obj.average / flag);

            double[] old_ordi_1 = new double[2];
            double[] old_ordi_2 = new double[2];
            old_ordi_1[0] = Math.Log10(obj.data_time[Convert.ToInt16(obj.average)]);
            old_ordi_1[1] = obj.data_deformation[Convert.ToInt16(obj.average)];
            old_ordi_2[0] = Math.Log10(obj.data_time[Convert.ToInt16(obj.average + 1)]);
            old_ordi_2[1] = obj.data_deformation[Convert.ToInt16(obj.average + 1)];

            obj.a_1 = (old_ordi_2[1] - old_ordi_1[1]) / (old_ordi_2[0] - old_ordi_1[0]);
            obj.b_1 = old_ordi_1[1] - old_ordi_1[0] * obj.a_1;

            double[] new_ordi_1 = new double[2];
            double[] new_ordi_2 = new double[2];

            new_ordi_1[1] = old_ordi_1[1] - (old_ordi_1[1] - obj.data_deformation[0]);
            new_ordi_1[0] = (new_ordi_1[1] - obj.b_1) / obj.a_1;
            new_ordi_2[1] = old_ordi_2[1] + (obj.data_deformation[13] - old_ordi_2[1]);
            new_ordi_2[0] = (new_ordi_2[1] - obj.b_1) / obj.a_1;

            // Create an empty table.
            DataTable table2 = new DataTable("Table1");

            // Add two columns to the table.
            table2.Columns.Add("Argument", typeof(Double));
            table2.Columns.Add("Value", typeof(Double));

            // Add data rows to the table.
            DataRow row = null;


            row = table2.NewRow();
            row["Argument"] = Math.Round(new_ordi_1[0], 6);
            row["Value"] = -Math.Round(new_ordi_1[1], 6);
            table2.Rows.Add(row);
            row = table2.NewRow();
            row["Argument"] = Math.Round(new_ordi_2[0], 6);
            row["Value"] = -Math.Round(new_ordi_2[1], 6);
            table2.Rows.Add(row);
            
            obj.Dt2 = table2;
            Session[ObjBieuDoThiNghiem.SESSION_NAME] = obj;
        }

        private void tim_tiep_tuyen_2()
        {
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null) return;
            double[] old_ordi_1 = new double[2];
            double[] old_ordi_2 = new double[2];
            old_ordi_1[0] = Math.Log10(obj.data_time[12]);
            old_ordi_1[1] = obj.data_deformation[12];
            old_ordi_2[0] = Math.Log10(obj.data_time[13]);
            old_ordi_2[1] = obj.data_deformation[13];

            obj.a_2 = (old_ordi_2[1] - old_ordi_1[1]) / (old_ordi_2[0] - old_ordi_1[0]);
            obj.b_2 = old_ordi_1[1] - old_ordi_1[0] * obj.a_2;

            double[] new_ordi_1 = new double[2];
            double[] new_ordi_2 = new double[2];

            new_ordi_1[1] = old_ordi_1[1] - (old_ordi_1[1] - obj.data_deformation[9]);
            new_ordi_1[0] = (new_ordi_1[1] - obj.b_2) / obj.a_2;
            new_ordi_2[1] = old_ordi_2[1];
            new_ordi_2[0] = old_ordi_2[0];

            // Create an empty table.
            DataTable table3 = new DataTable("Table3");

            // Add two columns to the table.
            table3.Columns.Add("Argument", typeof(Double));
            table3.Columns.Add("Value", typeof(Double));

            // Add data rows to the table.
            DataRow row = null;

            row = table3.NewRow();
            row["Argument"] = Math.Round(new_ordi_1[0], 6);
            row["Value"] = -Math.Round(new_ordi_1[1], 6);
            table3.Rows.Add(row);
            row = table3.NewRow();
            row["Argument"] = Math.Round(new_ordi_2[0], 6);
            row["Value"] = -Math.Round(new_ordi_2[1], 6);
            table3.Rows.Add(row);

            obj.Dt3 = table3;
            Session[ObjBieuDoThiNghiem.SESSION_NAME] = obj;
        }

        private void tim_s100_and_s50()
        {
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null) return;
            double x_100 = (obj.b_2 - obj.b_1) / (obj.a_1 - obj.a_2);
            double y_100 = (obj.b_2 - obj.b_1) / (obj.a_1 - obj.a_2) * obj.a_1 + obj.b_1;

            //Vẽ điểm giao 2 đường tiếp tuyến
            DataTable table4 = new DataTable("Table4");
            table4.Columns.Add("Argument", typeof(Double));
            table4.Columns.Add("Value", typeof(Double));
            DataRow row = null;
            row = table4.NewRow();
            row["Argument"] = Math.Round(x_100, 5);
            row["Value"] = -Math.Round(y_100, 5);
            table4.Rows.Add(row);
            obj.Dt4 = table4;
            Session[ObjBieuDoThiNghiem.SESSION_NAME] = obj;
            //chương trình nội suy t0
            double T_0 = 0.6;
            double S_0 = 0;
            for (int i = 0; i <= 13; i++)
            {
                if (obj.data_time[i] <= T_0 && T_0 <= obj.data_time[i + 1])
                {
                    S_0 = obj.data_deformation[i] + (obj.data_deformation[i + 1] - obj.data_deformation[i]) * (T_0 - obj.data_time[i]) / (obj.data_time[i + 1] - obj.data_time[i]);
                }
            }
            //chương trình nội suy t0/4
            double T_1_4 = T_0 / 4;
            double S_1_4 = 0;
            for (int i = 0; i <= 13; i++)
            {
                if (obj.data_time[i] <= T_1_4 && T_1_4 <= obj.data_time[i + 1])
                {
                    S_1_4 = obj.data_deformation[i] + (obj.data_deformation[i + 1] - obj.data_deformation[i]) * (T_1_4 - obj.data_time[i]) / (obj.data_time[i + 1] - obj.data_time[i]);
                }
            }

            double S0 = 2 * S_1_4 - S_0;
            double S50 = (y_100 + S0) / 2;            //s100 = y_100
            //chương trình nội suy S50
            double T50 = 0;
            for (int i = 0; i <= 13; i++)
            {
                if (obj.data_deformation[i] <= S50 && S50 <= obj.data_deformation[i + 1])
                {
                    T50 = (obj.data_time[i] + (obj.data_time[i + 1] - obj.data_time[i]) * (S50 - obj.data_deformation[i]) / (obj.data_deformation[i + 1] - obj.data_deformation[i]));
                }
            }

            double Cv = (0.197 * (Math.Pow(0.5 * (2 - S50), 2) / (T50 * 60))) * 1000;

            double P_0 = Convert.ToDouble(str_P_0);
            double P_1 = Convert.ToDouble(txt_cap_ap_luc.Text);
            double e_0 = Convert.ToDouble(str_e_0);
            double e_i = Convert.ToDouble(str_e_i);

            double e_1 = e_0 - (obj.data_deformation.Max() / 2) * (1 + e_0);
            double a = 10 * (e_1 - e_i) / (P_0 - P_1);
            double Kv = ((Cv * a) / (1 + e_i)) * 100;

            double mv = a / (1 + e_i);

            txt_Hdb.Text = "d 0 =  " + Math.Round(S0, 5).ToString() + " cm";
            txt_Hod.Text = "d100 = " + Math.Round(y_100, 5).ToString() + " cm";
            txt_Htb.Visible = false;
            txt_t90.Text = "t50 = " + Math.Round(T50, 2).ToString() + " min";
            txt_d90.Text = "d50 = " + Math.Round(S50, 4).ToString() + " cm";
            txt_Cv.Text = "Cv = " + Math.Round(Cv, 3).ToString() + " cm2/s";
            txt_Kv.Text = "Kv = " + Math.Round(Kv, 3).ToString() + " cm/s";

            /////////////////////////////////////////////////////////////////
            ////////////////////TRUYỀN DATA VỀ FORM THÔNG TIN////////////////
            var objTn = (ObjThiNghiem)Session[ObjThiNghiem.SESSION_NAME];
            if (objTn != null)
            {
                if (cap_ap_luc != "")
                {
                    int i = Convert.ToInt16(cap_ap_luc.Substring(4, 1));
                    objTn.P[i] = (P_1);
                    objTn.AH[i] = obj.data_deformation.Max();
                    objTn.hsr[i] = e_1;
                    objTn.a[i] = a;
                    objTn.T50[i] = T50;
                    objTn.S50[i] = S50;
                    objTn.Cv[i] = Cv;
                    objTn.Kv[i] = Kv;
                    objTn.mv[i] = mv;
                    Session[ObjThiNghiem.SESSION_NAME] = objTn;
                }
            }

            //Form1.cap_ap_luc = cap_ap_luc;
//            Form1.str_P = P_1.ToString();
//            Form1.str_AH = Convert.ToString(obj.data_deformation.Max());
//            Form1.str_e = e_1.ToString();
//            Form1.str_a = a.ToString();
//            Form1.str_T50 = T50.ToString();
//            Form1.str_S50 = S50.ToString();
//            Form1.str_Cv = Cv.ToString();
//            Form1.str_Kv = Kv.ToString();
//            Form1.str_mv = mv.ToString();
        }

        protected void bt_completed_Click(object sender, EventArgs e)
        {
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null) return;
            for (int j = 0; j <= 13; j++)
            {
                var ctrl = (ASPxSpinEdit)FindControl("txtData" + j);
                var lbl = (ASPxLabel)FindControl("lblData" + j);
                if (ctrl == null || lbl==null) continue;
                obj.data_deformation[j] = Convert.ToInt32(String.IsNullOrEmpty(ctrl.Text) ? 0 : ctrl.Number);
                obj.data_time[j] = Convert.ToDouble(lbl.Text);
            }
            
            obj.Dt1 = ve_bieu_do();


            if (obj.data_bieu_do == "Biểu thị theo căn(t)")
            {
                double data_Hbd = 2;
                double data_Hod = data_Hbd - obj.data_deformation.Max() / 1000;
                double data_Htb = (data_Hbd + data_Hod) / 2;
                double data_t90 = Math.Pow(4.36, 2);
                double data_d90 = Math.Pow(9.28, 2);
                double data_Cv = ((0.848 * (Math.Pow(data_Htb / 2, 2))) / (data_t90 * 60)) * 1000;//=((0.848*((Htb/2)^2))/(t90*60))*1000
                double data_Kv = 1;

                txt_Hdb.Text = "Hdb = " + Math.Round(data_Hbd, 3).ToString() + " cm";
                txt_Hod.Text = "Hod = " + Math.Round(data_Hod, 3).ToString() + " cm";
                txt_Htb.Text = "Hod = " + Math.Round(data_Htb, 3).ToString() + " cm";
                txt_t90.Text = "t90 = " + Math.Round(data_t90, 3).ToString() + " min";
                txt_d90.Text = "d90 = " + Math.Round(data_d90, 3).ToString() + " cm";
                txt_Cv.Text = "Cv = " + Math.Round(data_Cv, 3).ToString() + " cm2/s";
                txt_Kv.Text = "Kv = " + Math.Round(data_Kv, 3).ToString() + " cm/s";
            }
            else
            {
                tim_tiep_tuyen_1();
                tim_tiep_tuyen_2();
                tim_s100_and_s50();
            }

            Bieu_do_thi_nghiem_Load();
        }

        protected void cb_bieu_do_chon_SelectedIndexChanged(object sender, EventArgs e)
        {
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null) return;
            obj.data_bieu_do = cb_bieu_do_chon.SelectedItem.ToString();
        }

        protected void cb_change_data_SelectedIndexChanged(object sender, EventArgs e)
        {
            var obj = (ObjBieuDoThiNghiem)Session[ObjBieuDoThiNghiem.SESSION_NAME];
            if (obj == null) return;
            obj.data_input_data = cb_change_data.SelectedItem.ToString();
        }

    }
}